/*	
	stencil - action script 3 isometric game engine.

	http://code.google.com/p/stencilas3/
	
	Copyright (c) 2010 Max Zhuravkov, All Rights Reserved.

	Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
package stencil.core.engine.scene.view {
	
	import flash.display.DisplayObject;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import stencil.core.engine.display.IGraphicObject;
	import stencil.core.engine.events.VisibleAreaChangeEvent;
	import stencil.core.engine.IGrid;
	import stencil.core.engine.IMapArea;
	import stencil.core.engine.ITileSection;
	import stencil.core.engine.ISceneObject;
	import stencil.core.engine.scene.ISceneModel;
	import stencil.core.engine.events.TileDrawEvent;
	import stencil.core.engine.events.SceneUpdateEvent;
	import stencil.core.engine.events.TileRenderEvent;
	import stencil.core.engine.display.ITileRenderer;
	import stencil.core.engine.display.IDisplayList;
	import stencil.core.engine.display.IDisplayObject;
	import stencil.core.engine.scene.ISceneNode;
	import stencil.core.errors.RequiredPropertyError;
	import stencil.core.engine.utils.getClassName;
	
	
	/**
	 * ...
	 * @author Max Zhuravkov
	 */
	public class SceneView extends AbstractSceneView {
		
		private var _visibleArea:IMapArea;
		
		//------------------------------------------------------------------------------------------------
		// Constructor
		//------------------------------------------------------------------------------------------------
		
		public function SceneView() {
			super();
		}
		
		//------------------------------------------------------------------------------------------------
		// Protected properties
		//------------------------------------------------------------------------------------------------
		
		protected function set visibleArea(value:IMapArea):void {
			this._visibleArea = value;
			this.flagVisibleAreaChanged = true;
		}
		
		protected function get visibleArea():IMapArea {
			return this._visibleArea;
		}
		
		//------------------------------------------------------------------------------------------------
		// Protected methods
		//------------------------------------------------------------------------------------------------
		
		override protected function renderScene(viewPort:Rectangle, time:Number):void {
			
			if (this.flagViewPortChanged) {
				this.scrollRect = this.viewPort;
			}
			
			if (this.flagVisibleAreaChanged) {
				this.visibleAreaChanged(viewPort);
			}
			
			this.tileRenderer.grid = this.scene.tileGrid;
			this.tileRenderer.tileSettings = this.scene.tileSettings;
			this.tileRenderer.render();
			
			for (var i:int = 0; i < this.container.numChildren; i ++ ) {
				var diplayObject:DisplayObject = this.container.getChildAt(i);
				var component:IGraphicObject = this.components[diplayObject.name];
				
				component.render(viewPort, time);
			}
			
			this.additionalRendering();
		}
		
		protected function checkState():void {
			if (!this.scene) {
				throw new RequiredPropertyError(this, "scene");
			}
			
			if (!this.tileRenderer) {
				throw new RequiredPropertyError(this, "tileRenderer");
			}
			
			if (!this.viewPort) {
				throw new RequiredPropertyError(this, "viewPort");
			}
		}
		
		protected function additionalRendering():void {
			
		}
		
		override protected function sceneAdded(scene:ISceneModel):void {
			scene.addEventListener(TileDrawEvent.STN_TILE_DRAW, this.tileDrawHandler);
			scene.addEventListener(SceneUpdateEvent.STN_ADD_OBJECT, this.addObjectHandler);
			scene.addEventListener(SceneUpdateEvent.STN_REMOVE_OBJECT, this.addObjectHandler);
			scene.addEventListener(VisibleAreaChangeEvent.STN_VISIBLE_AREA_CHANGE, this.visibleAreaChangeHandler);
		}
		
		override protected function sceneRemoved(scene:ISceneModel):void {
			scene.removeEventListener(TileDrawEvent.STN_TILE_DRAW, this.tileDrawHandler);
			scene.removeEventListener(SceneUpdateEvent.STN_ADD_OBJECT, this.addObjectHandler);
			scene.removeEventListener(SceneUpdateEvent.STN_REMOVE_OBJECT, this.addObjectHandler);
			scene.removeEventListener(VisibleAreaChangeEvent.STN_VISIBLE_AREA_CHANGE, this.visibleAreaChangeHandler);
			
			tileRenderer.clear();
			this.clearDisplayLists();
		}
		
		override protected function tileRendererAdded(tileRender:ITileRenderer):void {
			tileRenderer.addEventListener(TileRenderEvent.STN_SECTION_CREATE, this.sectionCreateHandler);
			tileRenderer.addEventListener(TileRenderEvent.STN_SECTION_UPDATE, this.sectionUpdateHandler);
			tileRenderer.addEventListener(TileRenderEvent.STN_SECTION_REMOVE, this.sectionRemoveHandler);
		}
		
		override protected function tileRendererRemoved(tileRender:ITileRenderer):void {
			tileRenderer.removeEventListener(TileRenderEvent.STN_SECTION_CREATE, this.sectionCreateHandler);
			tileRenderer.removeEventListener(TileRenderEvent.STN_SECTION_UPDATE, this.sectionUpdateHandler);
			tileRenderer.removeEventListener(TileRenderEvent.STN_SECTION_REMOVE, this.sectionRemoveHandler);
		}
		
		
		protected function visibleAreaChangeHandler(event:VisibleAreaChangeEvent):void {
			this.visibleArea = event.area;
		}
		
		/**
		 * Called after view port has been changed.
		 * Updates display lists. Removes not visible object, adds new ones and updates positions of the remainder.
		 * 
		 * @param	viewPort	the current view port.
		 */
		protected function visibleAreaChanged(viewPort:Rectangle):void {
			var rect:Rectangle = this.visibleArea.rect;
			var sections:Array = this.visibleArea.sections;
			var objects:Array = this.visibleArea.objects;
			var objectGrid:IGrid = this.scene.objectGrid;
			
			this.tileRenderer.draw(sections);
			
			for (var i:int = 0; i < this.componentNumber; i ++ ) {
				var o:IGraphicObject = this.getComponentAt(i);
				if (o is IDisplayList) {
					var list:IDisplayList = o as IDisplayList;
					
					for each(var displayObject:IDisplayObject in list.children) {
						var sceneObject:ISceneObject = displayObject.owner;
						var p:Point = objectGrid.getCellPositionAt(sceneObject.position, false);
						var childRect:Rectangle = sceneObject.bounds.rect;
						
						if (!childRect.intersects(rect)) {
							this.removeDisplayObject(list, displayObject)
						}else {
							this.updateDisplayObject(list, displayObject);
						}
					}
				}
			}
			
			this.addNewObjects(viewPort, objects);
		}
		
		/**
		 * Called during display list update.
		 * Adds new objects.
		 * 
		 * @param	viewPort	the current view port.
		 * @param	objects		array that contains all currently accessable objects.
		 */
		protected function addNewObjects(viewPort:Rectangle, objects:Array):void {
			var displayListChanged:Boolean = false;
		
			for each(var sceneObject:ISceneObject in objects) {
				var displayList:IDisplayList = this.getDisplayList(sceneObject, false);
				if (!displayList) {
					continue;
				}
				var o:IDisplayObject = displayList.find(sceneObject.id);
				
				if (!o) {
					var displayObject:IDisplayObject = this.createDisplayObject(sceneObject);
					this.addDisplayObject(displayList, displayObject);
				}
				
				displayList.invalidate();
			}
		}
		
		/**
		 * Adds the display object to the specified display list.
		 * 
		 * @param	list	the display list.
		 * @param	displayObject	the display object.
		 */
		protected function addDisplayObject(list:IDisplayList, displayObject:IDisplayObject):void {
			list.add(displayObject);
		}
		
		/**
		 * Removes the display object from the specified display list.
		 * 
		 * @param	list	the display list.
		 * @param	displayObject	the display object.
		 */
		protected function removeDisplayObject(list:IDisplayList, displayObject:IDisplayObject):void {
			list.remove(displayObject);
			
			this.displayObjectFactory.releaseObject(displayObject);
			
			displayObject.owner = null;
		}
		
		/**
		 * Update the display object from the specified display list.
		 * 
		 * @param	list	the display list.
		 * @param	displayObject	the display list.
		 */
		protected function updateDisplayObject(list:IDisplayList, displayObject:IDisplayObject):void {
			list.update(displayObject);
		}
		
		
		/**
		 * Called when the given tile section is added or updated.
		 * Updates tile section position.
		 * 
		 * @param	list
		 * @param	section
		 */
		protected function updateSectionPosition(list:IDisplayList, section:ITileSection):void {
			if (list.calculateTilePositions) {
				return;
			}
			
			var point:Point = this.scene.tileGrid.getCellPosition(section.rect.x, section.rect.y, true);
			var tile:IDisplayObject = this.tileRenderer.getDisplayObject(section);
			var sprite:DisplayObject = tile.content;

			sprite.x = point.x - sprite.width / 2;
			sprite.y = point.y;
		}
		
		/**
		 * Called when the given tile section is added to display list.
		 * 
		 * @param	tiles	the tile section.
		 */
		protected function tileSectionAttached(tiles:ITileSection):void {
			
		}
		
		/**
		 * Called when the given tile section is removed from display.
		 * 
		 * @param	tiles	the tile section.
		 */
		protected function tileSectionDetached(tiles:ITileSection):void {
			
		}
		
		/**
		 * Called when the given tile section is updated.
		 * 
		 * @param	tiles	the tile section.
		 */
		protected function tileSectionUpdated(tiles:ITileSection):void {
			
		}
		
		/**
		 * Add object listener.
		 */
		protected function addObjectHandler(event:SceneUpdateEvent):void {
			var o:ISceneObject = event.object;
			var displayList:IDisplayList = this.getDisplayList(o, false);
			
			
			if (displayList) {
				var displayObject:IDisplayObject = this.createDisplayObject(o);
				
				this.addDisplayObject(displayList, displayObject);
			}
		}
		
		/**
		 * Remove object listener.
		 */
		protected function removeObjectHandler(event:SceneUpdateEvent):void {
			var o:ISceneObject = event.object;
			var displayList:IDisplayList = this.getDisplayList(o, false);
			
			if (displayList) {
				var displayObject:IDisplayObject = displayList.find(o.id);
				
				this.removeDisplayObject(displayList, displayObject);
			}
		}
		
		/**
		 * Creates display object for the given scene object.
		 * 
		 * @param	o	the scene object.
		 * 
		 * @return an IDisplayObject instance.
		 */
		protected function createDisplayObject(o:ISceneObject):IDisplayObject {
			var displayObject:IDisplayObject = this.displayObjectFactory.createObject(o.type, o, o.id) as IDisplayObject;
			
			if (!displayObject) {
				throw new Error("Class '" + getClassName(displayObject) + "' does not conform to '" + getClassName(IDisplayObject) + "'.");
			}
			
			return displayObject;
		}
		
		/**
		 * Returns the display list for the specified scene object.
		 * 
		 * @param	o	the scene object.
		 * @param	required	whether display list is required or not.
		 * 
		 * @return	the display list to which the given scene object should be added to.
		 */
		protected final function getDisplayList(o:ISceneObject, required:Boolean):IDisplayList {
			if (!this.displayFilter) {
				throw new Error("displayFilter property has not been set.");
			}
			var displayListName:String = this.displayFilter.filter(o);
			var displayList:IDisplayList = displayListName ? this.getComponentByName(displayListName) as IDisplayList : null;
			if (displayListName && !displayList) {
				throw new Error("Unable to find the display list with name '" + displayListName + "'.");
			}
			if (required && !displayList) {
				throw new Error("Unable to find a display list for an object '" + o + "'.");
			}
			
			return displayList;
		}
		
		/**
		 * Clears display lists.
		 */
		protected function clearDisplayLists():void {
			for (var i:int = 0; i < this.componentNumber; i ++ ) {
				var o:IGraphicObject = this.getComponentAt(i);
				if (o is IDisplayList) {
					var displayList:IDisplayList = o as IDisplayList;
					displayList.clear();
				}
			}
		}
		
		//------------------------------------------------------------------------------------------------
		// Private methods
		//------------------------------------------------------------------------------------------------
		
		private function sectionCreateHandler(event:TileRenderEvent):void {
			var section:ISceneNode = event.section as ISceneNode;
			var sprite:IDisplayObject = this.tileRenderer.getDisplayObject(section);
			var displayList:IDisplayList = this.getDisplayList(section, true);
			
			displayList.add(sprite);
			
			this.updateSectionPosition(displayList, section);
			this.tileSectionAttached(section);
		}
		
		private function sectionUpdateHandler(event:TileRenderEvent):void {
			var section:ISceneNode = event.section as ISceneNode;
			var sprite:IDisplayObject = this.tileRenderer.getDisplayObject(section);
			var displayList:IDisplayList = this.getDisplayList(section, true);
			
			displayList.update(sprite);
			
			this.updateSectionPosition(displayList, section);
			this.tileSectionUpdated(section);
		}
		
		private function sectionRemoveHandler(event:TileRenderEvent):void {
			var section:ITileSection = event.section; 
			var sprite:IDisplayObject = this.tileRenderer.getDisplayObject(section);
		
			if (sprite) {
				var displayList:IDisplayList = this.getDisplayList(section, true);
				displayList.remove(sprite);
				this.tileSectionDetached(section);
			}
		}
		
		private function tileDrawHandler(event:TileDrawEvent):void {
			for each(var section:ITileSection in event.sections){
				this.tileRenderer.redrawTiles(section);
			}
		}
		
	}

}